package patrol.mobile.com.mobilepatrol.utils;

import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import okhttp3.Call;
import patrol.mobile.com.mobilepatrol.activity.office.AdviceDetailActivity;
import patrol.mobile.com.mobilepatrol.api.Urls;
import patrol.mobile.com.mobilepatrol.utils.net.HttpSender;
import retrofit2.http.Url;
import top.zibin.luban.CompressionPredicate;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * Created by K on 2018/9/18.
 * des: 图片压缩+上传
 */
public class LuBanHelper {

    private static final String TAG = "LuBanHelper";
    private Context context;
    private List<File> files;
    private ProgressDialog dialog;
    private final String LOADING_TITLE = "正在压缩...";
    private String baseUrl;
    private List<Map<String, String>> map;


    public LuBanHelper(Context context, List<File> files, List<Map<String, String>> map) {
        this.context = context;
        this.files = files;
        this.map = map;
        baseUrl = (String) SPUtils.get(Constants.current_ser, "");
    }

    public void compression(final StringCallback callback) {
        Luban.with(context)
                .load(files)
                .ignoreBy(100)
                .setTargetDir(getPath())
                .filter(new CompressionPredicate() {
                    @Override
                    public boolean apply(String path) {
                        return !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif"));
                    }
                })
                .setCompressListener(new OnCompressListener() {
                    int count = -1;

                    @Override
                    public void onStart() {
                        // 压缩开始前调用，可以在方法内启动 loading UI
                        showDialog();
                        count++;
                    }

                    @Override
                    public void onSuccess(File file) {
                        // 压缩成功后调用，返回压缩后的图片文件
                        dismissDialog();

                        List<File> files = new ArrayList<>();
                        files.add(file);
                        HttpSender sender = new HttpSender(context, baseUrl, Urls.IMG_UP_LOAD);
                        Map<String, String> map = LuBanHelper.this.map.get(count);
                        Log.i(TAG, "filemap: "+map);
                        sender.upImgs2(file, map, callback);
                    }

                    @Override
                    public void onError(Throwable e) {
                        // 当压缩过程出现问题时调用
                        dismissDialog();
                        Toast.makeText(context, "压缩失败，请重试", Toast.LENGTH_SHORT).show();
                    }
                }).launch();
    }

    private void showDialog() {
        if (context == null) {
            return;
        }
        if (dialog == null) {
            dialog = new ProgressDialog(context);
            dialog.setMessage(LOADING_TITLE);
        }
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }

    public void dismissDialog() {
        if (dialog != null && dialog.isShowing())
            dialog.dismiss();
    }

    private String getPath() {
        String path = Environment.getExternalStorageDirectory() + "/Luban/image/";
        File file = new File(path);
        if (file.mkdirs()) {
            return path;
        }
        return path;
    }

    private int[] computeSize(File srcImg) {
        int[] size = new int[2];

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        options.inSampleSize = 1;

        BitmapFactory.decodeFile(srcImg.getAbsolutePath(), options);
        size[0] = options.outWidth;
        size[1] = options.outHeight;

        return size;
    }

    private void showResult(String position, File file) {
        int[] thumbSize = computeSize(file);
        String thumbArg = String.format(Locale.CHINA, "参数：%d*%d, %dk", thumbSize[0], thumbSize[1], file.length() >> 10);
        Log.i(TAG, "showResult: " + position + "--" + thumbArg);
    }
}
